package com.ums.providerboot.service;

import com.ums.providerboot.framework.DistributedRedisLock;
import com.ums.providerboot.framework.RedisGlobalLock;
import com.ums.providerboot.framework.RedissonManager;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@RestController
public class PayService {

    @Resource
    private RedisGlobalLock redisGlobalLock;

    @PostMapping("/pay")
    public void pay() throws InterruptedException {
        String key = UUID.randomUUID().toString();
        if (redisGlobalLock.tryLock(key)) {
            System.out.println(String.format("###获得锁: %s, 开始业务处理", key));
            try{
                TimeUnit.SECONDS.sleep(5);
            }finally {
                redisGlobalLock.unlock(key);
                System.out.println(String.format("###释放锁: %s", key));
            }

        }else{
            //Ensure
        }
    }

    @PostMapping("/pay2")
    public void pay2() throws InterruptedException {
        String key = UUID.randomUUID().toString();
        System.out.println(String.format("###获得锁: %s, 开始业务处理", key));
        try{
            if (DistributedRedisLock.acquire(key)) {
                //TimeUnit.SECONDS.sleep(1);
                System.out.println("业务处理, ThreadID:"+Thread.currentThread().getId());
            }
        }finally {
            DistributedRedisLock.release(key);
            System.out.println(String.format("###释放锁: %s", key));
        }
    }
}
